package com.spring.web.interceptor.ehcache;

import java.io.Serializable;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

public class MethodCacheInterceptor implements MethodInterceptor, InitializingBean {

	private static final Log logger = LogFactory.getLog(MethodCacheInterceptor.class);
	
	private Cache cache;
	
	public void setCache(Cache cache){
		this.cache = cache;
	}
	
	public MethodCacheInterceptor(){}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		Assert.isNull(cache, "methodCacheInterceptor -- need a cache, please use setCache(cache) create it");
	}

	/**
	 * 
	 */
	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		String targetName = invocation.getThis().getClass().getName();
		String methodName = invocation.getMethod().getName();
		Object[] arguments = invocation.getArguments();
		Object result;
		
		logger.debug("methodCacheInterceptor -- find object from cache is " + cache.getName());
		
		String cacheKey = getCacheKey(targetName, methodName, arguments);
		Element element = cache.get(cacheKey);
		
		if(element != null){
			logger.debug("methodCacheInterceptor -- hold up method, get method result and create cache ...");
			result = invocation.proceed();
			element = new Element(cacheKey, (Serializable)result);
			cache.put(element);
		}
		
		return element.getValue();
	}

	/**
	 * 获得cache key的方法,cache key是Cache中的一个Element唯一标识
	 * cache key -- 包名+类名+方法名
	 * @param targetName
	 * @param methodName
	 * @param arguments
	 * @return
	 */
	private String getCacheKey(String targetName, String methodName, Object[] arguments) {
		StringBuffer strBuf = new StringBuffer();
		strBuf.append(targetName).append(".").append(methodName);
		if(arguments != null && arguments.length > 0){
			for(int i=0; i<arguments.length; i++){
				strBuf.append(".").append(arguments[i]);
			}
		}
		return strBuf.toString();
	}

}
